from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3

app = Flask(__name__)

# 启用跨域
CORS(app)

# 查询最近水位数据和警戒线
def query_current_water_level(station_name):
    conn = sqlite3.connect('hydrology.db')
    cursor = conn.cursor()

    # 查询警戒线
    cursor.execute(
        "SELECT water_level_limit FROM water_level_data WHERE station_name = ?",
        (station_name,)
    )
    alert_level = cursor.fetchone()
    if not alert_level:
        conn.close()
        return {"error": f"No alert level data found for station: {station_name}"}
    alert_level = alert_level[0]

    # 查询最近 5 条水位数据
    cursor.execute(
        """
        SELECT observation_time, precipitation
        FROM hydrology_data
        WHERE station_name = ?
        ORDER BY observation_time DESC
        LIMIT 5
        """,
        (station_name,)
    )
    recent_data = cursor.fetchall()
    conn.close()

    if not recent_data:
        return {"error": f"No water level data found for station: {station_name}"}

    # 格式化数据
    return {
        "alert_level": alert_level,
        "recent_data": [
            {"time": row[0], "precipitation": row[1]} for row in recent_data
        ]
    }

@app.route('/current_water_level', methods=['POST'])
def current_water_level():
    data = request.json
    station_name = data.get("station_name")
    if not station_name:
        return jsonify({"error": "Missing station_name"}), 400

    result = query_current_water_level(station_name)
    if "error" in result:
        return jsonify(result), 404

    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)